#!/bin/sh

[ -z $1 ] && echo "Usage: $0 <tenant_id>" && exit 1

TENANT_ID=$1
ID=$(echo "raspbian ubuntucore arch debian ubuntu" | cut -d' ' -f$(shuf -i1-5 -n1))
PRETTY_NAME=$ID
MACADDR=$(echo -n 02; dd bs=1 count=5 if=/dev/random 2>/dev/null | hexdump -v -e '/1 ":%02X"')

PRIVATE_KEY_FILE=$(mktemp -u)
PUBLIC_KEY_FILE=$(mktemp -u)

openssl genpkey -algorithm RSA -out $PRIVATE_KEY_FILE -pkeyopt rsa_keygen_bits:2048 2> /dev/null
openssl rsa -in $PRIVATE_KEY_FILE -out $PUBLIC_KEY_FILE -pubout 2> /dev/null

PUBLIC_KEY=$(cat $PUBLIC_KEY_FILE)

rm -f $PRIVATE_KEY_FILE
rm -f $PUBLIC_KEY_FILE

JSON=$(cat <<EOF
{
  "sessions": [],
  "info": {
    "id": "$ID",
    "pretty_name": "$PRETTY_NAME",
    "version": "latest",
    "platform": "native"
  },
  "identity": {
    "mac": "$MACADDR"
  },
  "public_key": "$PUBLIC_KEY",
  "tenant_id": "$TENANT_ID"
}
EOF
)

echo $JSON | http post http://localhost/api/devices/auth && echo "Device added!"
